import React, { Component } from 'react'
import { connect } from 'dva';
import Link from 'umi/link';

import { Table } from 'antd';

import Form from './components/SearchReportForm';

import { getBtnList } from '@/utils/util';

export interface IProps {
  dispatch?: ({ type }: { type: string, payload?: any }) => Promise<any>;
  children?: React.ReactNode;
  loading?: boolean;
  buttons?: Array<any>;
  list?: {
    data: Array<any>;
    dataCnt: number
  };
  cond?: {
    pageSize: number;
  }
}

export interface IState {
  current: number,
  isChangePage?: boolean,
}

@connect(({ task_month, loading, menu }) => ({
  cond: task_month.cond || {},
  list: task_month.reportList || {},
  loading: loading.effects['task_month/queryReportPage'],
  buttons: menu.buttons,
}))
class Reports extends Component<IProps, IState> {

  state:IState = {
    current: 1,
  }

  queryData(pageNum = 1) {
    const { dispatch, cond } = this.props;
    dispatch({ 
      type: 'task_month/queryReportPage', 
      payload: { pageNum, ...cond } 
    })
  }

  onShowSizeChange = (current, pageSize) => {
    const { dispatch, cond } = this.props;
    cond.pageSize = pageSize;
    this.setState({ current: 1 }, () => {
      dispatch({
        type: 'task_month/updateReportCond',
        payload: cond
      })
    })
  }

  componentDidMount() {
    this.queryData()
  }

  initCurrent = () => {
    this.setState({ current: 1 })
  };
  
  render() {

    const { list, buttons } = this.props;
    const { dataCnt, data } = list;

    const btnList = getBtnList(buttons);

    const pagination = {
      total: dataCnt,
      showTotal: total => `共 ${total} 条`,
      showSizeChanger: true,
      current: this.state.current,
      pageSizeOptions: ['10', '20', '50', '100'],
      onShowSizeChange: this.onShowSizeChange,
      onChange: (current) => {
        this.setState({
          current,
          isChangePage: true
        }, () => this.queryData(current));
      },
    };
    
    const columns = [{
      title: '报告名称',
      dataIndex: 'name',
    }, {
      title: '检查人',
      dataIndex: 'users',
      render: (text) => (
        Array.isArray(text) ? text.map(u => u.name).join(', ') : ''
      )
    }, {
      title: '检查时间',
      dataIndex: 'doneTime',
    }, {
      title: '操作', key: 'x', render: (record) => {
        return (
          <div style={{ display: 'flex' }}>
            {
              btnList['查看'] && <>
                <Link to={`/data/task_month/${record.id}/report`}>查看</Link>
              </>
            }
          </div>
        )
      }
    }]
    
    return (
      <>
        <Form current={this.state.current} initCurrent={this.initCurrent} new={!!btnList['新增']} />
        <Table
          columns={columns}
          pagination={pagination}
          dataSource={data}
          rowKey='id'
          loading={this.props.loading}
          bordered
        />
      </>
    )
  }
}

export default  Reports;